/** 消息来源 */
const MESSAGE_SOURCE = {
    /** 本地应用（设计器） */
    NATIVE: 'native',
    /** 运行时 */
    RUNTIME: 'runtime',
};
const NATIVE_APP_NAME = 'yonyou.rpa.chromeapp';

export function reconnectToNativeApp() {
    console.log('判断休眠状态');
    if (typeof globalThis.nativePort === 'undefined') {
        globalThis.nativePort = chrome.runtime.connectNative(NATIVE_APP_NAME);
        globalThis.nativePort.onMessage.addListener((message) => {
            try {
                if (!message || typeof message !== 'object') {
                    console.error('消息格式错误，只支持json格式', message);
                } else {
                    globalThis.nativeHost.initFunc(message, MESSAGE_SOURCE.NATIVE);
                }
            } catch (error) {
                console.error('Error processing message:', error);
            }
        });
        globalThis.nativePort.onDisconnect.addListener(() => {
            console.log('Native connection lost, attempting to reconnect...');
            globalThis.nativePort = undefined;
        });
        console.log('Reconnected to native app.');
    } else {
        // globalThis.nativePort.disconnect();
        // globalThis.nativePort = undefined;
        // postMessage ping
    }
}

// 创建个闹钟，定时检测是否中断
async function createAlarm() {
    const ALARM_NAME = 'keep-alive-alarm';
    const alarm = await chrome.alarms.get(ALARM_NAME);
    if (typeof alarm === 'undefined') {
        chrome.alarms.create(ALARM_NAME, {
            delayInMinutes: 0.3, // 延迟 18s
            periodInMinutes: 0.3, // 每 18s 秒触发一次
        });
        reconnectToNativeApp(); // 立即执行一次
    }
}

createAlarm();

chrome.alarms.onAlarm.addListener(reconnectToNativeApp);
